package com.ruoyi.oss.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.oss.entity.Chunk;
import com.ruoyi.oss.entity.UploadRes;
import com.ruoyi.oss.service.IOssService;
import com.ruoyi.oss.template.OssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OssServiceImpl implements IOssService {

    private static String bucketName = "hello";

    private static String tempBucketName = "test";

    @Autowired
    private OssTemplate ossTemplate ;

    @Override
    public UploadRes upload(Chunk chunk) {

        if(chunk.getTotalChunks().equals(1)) {
            Date now = DateUtils.getNowDate();
            String year = DateUtils.parseDateToStr("yyyy", now);
            String month = DateUtils.parseDateToStr("MM", now);
            String day = DateUtils.parseDateToStr("dd", now);
            String object = year + "/" + month + "/" + day + "/" + chunk.getIdentifier() + "/" + chunk.getFilename() ;
            ossTemplate.putFile(bucketName, object, chunk.getFile());
            return new UploadRes(false) ;
        } else {
            String object = chunk.getFilename() + "/" + chunk.getIdentifier() + "/" + chunk.getChunkNumber() + ".chunk" ;
            ossTemplate.putFile(tempBucketName, object, chunk.getFile());
            return new UploadRes(true) ;
        }
    }

    @Override
    public UploadRes merge(Chunk chunk) {

        String prefix = chunk.getFilename() + "/" + chunk.getIdentifier() + "/"  ;
        List<String> listObjects = ossTemplate.listObjects(tempBucketName, prefix);
        Date now = DateUtils.getNowDate();
        String year = DateUtils.parseDateToStr("yyyy", now);
        String month = DateUtils.parseDateToStr("MM", now);
        String day = DateUtils.parseDateToStr("dd", now);
        ossTemplate.merge(bucketName, year + "/" + month + "/" + day + "/" + chunk.getIdentifier() + "/" + chunk.getFilename(), listObjects);
        return null;
    }
}
